<template>
  <MainBox one="权限管理" two="角色列表">
    <div>
      <el-row>
        <el-col>
          <!-- 添加角色的 -->
          <el-button type="primary" @click="addDialog">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" style="width:100%" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级菜单的行 -->
            <el-row
              :class="['bdbottom',i1==0?'bdtop':'','vcenter']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级菜单的列 -->
              <el-col :span="5">
                <el-tag closable @close="removeRights(scope.row,item1.id)">
                  {{item1.authName}}
                  <i class="el-icon-caret-right"></i>
                </el-tag>

                <!-- 二级 三级  菜单的列 -->
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="[i==0 ?'':'bdtop','vcenter']"
                  v-for="(item2,i) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRights(scope.row,item2.id)">
                      {{item2.authName}}
                      <i class="el-icon-caret-right"></i>
                    </el-tag>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3,i) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRights(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button icon="el-icon-edit" type="primary" size="mini" @click="editContent">编辑</el-button>
            <el-button
              icon="el-icon-delete"
              type="danger"
              size="mini"
              @click="deleteContent(scope.row.id)"
            >删除</el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                icon="el-icon-setting"
                type="warning"
                size="mini"
                @click="settingLog(scope.row)"
              >分配角色</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="closeAdd">
      <el-form
        :model="addForm"
        :rules="rules"
        ref="addForm"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="用户描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc" @keydown.enter="handel"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDialogVis()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="编辑用户" :visible.sync="editdialogs" width="50%">
      <el-form
        :model="editForm"
        :rules="rules"
        ref="editForm"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名称" prop="email">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="用户描述" prop="email">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogs = false">取 消</el-button>
        <el-button type="primary">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 权限分配 -->
    <el-dialog title="权限分配" :visible.sync="settingdialogs" width="50%" @close="closeSettingslist">
      <el-tree
        :data="settingsList"
        :props="defaultProps"
        :default-expand-all="true"
        node-key="id"
        show-checkbox 
        :default-checked-keys="deFaultArr"
        ref="treeRef"
      
      ></el-tree>
      <!-- default-checked-keys 就是 这个默认选中的key数组 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="settingdialogs = false">取 消</el-button>
        <el-button type="primary" @click="confirmsettings">确 定</el-button>
      </span>
    </el-dialog>
  </MainBox>
</template>

<script>
//  不需要导入，因为全局已经注册
//  import MainBox from '../pubom/MainBox.vue'
export default {
  data() {
    return {
      rolesList: [],
      settingsList: [],
      dialogVisible: false,
      editdialogs: false,
      settingdialogs: false,
      addForm: {
        roleName: "",
        roleDesc: ""
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色", trigger: "blur" },
          { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10个字符", trigger: "blur" }
        ]
      },
      editForm: {
        roleName: "",
        roleDesc: ""
      },
      ///树形控件的属性绑定对对象
      defaultProps: {
        // 显示那个字段
        label: "authName",
        // 子节点显示哪个节点
        children: "children"
      },
      // 默认选中的
      deFaultArr: [],
      //角色id
      roleId:''
    };
  },
  // components:{
  //     MainBox
  // },
  created() {
    this.getrolesList();
    // 权限列表数据
    // this.getsettings()
  },

  methods: {
    //关闭添加用户弹窗触发的事件
    closeAdd() {
      this.$refs.addForm.resetFields();
    },

    async getrolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error("查询失败");
      this.rolesList = res.data;
    },
    addDialog() {
      // 添加角色模块
      this.dialogVisible = true;
    },
    addDialogVis() {
      this.$refs.addForm.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post("roles", this.addForm);
        // console.log(res);
        if (res.meta.status != 201) return this.$message.error("添加失败");
        this.getrolesList();
        this.dialogVisible = false;
      });
    },
    // 编辑角色模块
    editContent() {
      this.editdialogs = true;
    },
    handel() {
      console.log(123);
    },
    //删除按钮模块
    async deleteContent(id) {
      // console.log(id);
      const confimDel = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confimDel !== "confirm") {
        return this.$message.error("取消了删除");
      }
      const res = await this.$http.delete("roles/" + id);
      // console.log(res);
      if (res.status !== 200) return this.$message.error("删除失败");
      this.getrolesList();
    },

    async removeRights(role, rightId) {
      // 删除展开列的
      const confimRights = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // console.log(confimRights);
      if (confimRights !== "confirm") return this.$message.error("取消了删除");
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) return this.$message.info("删除失败");
      role.children = res.data;
    },
    // 分配角色
    async settingLog(role) {
      this.roleId=role.id
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) return this.$message.error("查询失败");
      // console.log(res.data);
      this.settingsList = res.data;
      // console.log(this.settingsList);
      this.getLeafKeys(role, this.deFaultArr);
      this.settingdialogs = true;
    },
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach(item => this.getLeafKeys(item, arr));
    },
    closeSettingslist() {
      this.deFaultArr = [];
      // console.log(this.deFaultArr);
    },
    // 分配角色确认按钮
   async confirmsettings(){
        var keys=[...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()]
        var keyId=keys.join(',')
    const {data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{
      rids:keyId
    })
    if(res.meta.status!==200) return this.$message.error('添加失败')
    this.$message.success('添加成功')
    this.getrolesList();
    this.settingdialogs=false;

    }
  }
};
</script>
<style lang="less" scoped>
.el-tag {
  margin: 15px;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.bdtop {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>